<?php

namespace app\common\model;

use basic\ModelBasic;

class CouponRecords extends ModelBasic
{
	use \traits\ModelTrait;

    // 未使用
    const STATUS_UNUSE    = 1;
    // 已使用
    const STATUS_USED     = 2;
    // 已过期
    const STATUS_EXPIRED  = 3;
    // 已作废（可能没用，占位吧）
    const STATUS_ABLISHED = 4;
    // 状态：1=未使用 2=已使用 3=已过期 4=已作废
    public static $status = [
        1 => '未使用',
        2 => '已使用',
        3 => '已过期',
        4 => '已作废',
    ];

    // 1:自行领取 2:分享领取 3:后台发放
    public static $obtain_type = [
        1 => '自行领取',
        2 => '分享领取',
        3 => '后台发放',
        4 => '商城兑换',
    ];

    // 1=线上抵扣，2=线下核销
    public static $use_type = [
        1 => '线上抵扣',
        2 => '线下核销',
        3 => '后台核销',
    ];

	/**
	 * 设置where条件
	 * @Author   FW
	 * @DateTime 2021-01-12
	 * @Email    123763712@qq.com
	 * @param    [type]           $where [description]
	 * @param    string           $alias [description]
	 * @param    [type]           $model [description]
	 */
	public static function setWhere($where,$alias='m',$model=null){
        $model = $model===null ? new self() : $model;

        $model->alias($alias);

        if ( isset($where['coupon_id']) && $where['coupon_id'] != '' ) {
            $model->where(sprintf('%s.coupon_id=%d' , $alias , $where['coupon_id']));
        }

        if ( isset($where['uid']) && $where['uid'] != '' ) {
            $model->where(sprintf('%s.uid=%d' , $alias , $where['uid']));
        }

        if ( isset($where['mobile']) && $where['mobile'] != '' ) {
            $qSql = "{$alias}.uid IN (SELECT uid FROM eb_user WHERE mobile LIKE '%". $where['mobile'] ."%')";
            $model->where($qSql);
        }

        if ( isset($where['status']) && $where['status'] != '' ) {
            $model->where(sprintf('%s.status=%d' , $alias , $where['status']));
        }

        if ( isset($where['order']) && $where['order'] != '' ) {
            $model->order(sprintf('%s.%s' , $alias, $where['order']));
        } else {
            $model->order(sprintf('%s.expire_time ASC, %s.obtain_time DESC' , $alias , $alias));
        }
        return $model;
    }

    /**
     * 列表
     * @Author   FW
     * @DateTime 2020-09-24
     * @Email    123763712@qq.com
     * @param    [type]
     * @return   [type]
     */
    public static function getList($where){
    	$count = self::setWhere($where,'m')
        ->join('__COUPON__ c','m.coupon_id = c.id')
        ->count();
    	$data  = [];
    	if ( $count == 0 ) {
    		return compact('data','count');
    	}

        $data=self::setWhere($where,'m')
        ->field('m.*,u.nickname,u.mobile,c.title as coupon_name,c.coupon_value')
        ->join('__USER__ u','m.uid = u.uid')
        ->join('__COUPON__ c','m.coupon_id = c.id')
        ->page($where['page'] ?? 1, $where['limit'] ?? 10)
        ->select();

        if ( !empty($data) ) {
        	$data = $data->toArray();
        	$data = static::process_list($data);
        }

        return compact('data','count');
    }

    /**
     * 列表
     * @Author   FW
     * @DateTime 2020-09-24
     * @Email    123763712@qq.com
     * @param    [type]
     * @return   [type]
     */
    public static function getOne($id){
        $data=self::alias('m')
        ->field('m.*,u.nickname,u.mobile,c.title as coupon_name,c.coupon_value,cr.rdesc')
        ->join('__USER__ u','m.uid = u.uid')
        ->join('__COUPON__ c','m.coupon_id = c.id')
        ->join('__COUPON_RULES__ cr','c.use_rule_id = cr.id')
        ->where('m.id',$id)
        ->find();

        if ( !empty($data) ) {
            $data = $data->toArray();
            $data = static::process_list([$data]);
        }

        return $data[0];
    }

    /**
     * 处理列表数据
     * @Author   FW
     * @DateTime 2021-01-12
     * @Email    123763712@qq.com
     * @param    array            $list [description]
     * @return   [type]                 [description]
     */
    public static function process_list (array $list)
    {
        foreach ($list as $key => &$item) {
            $item['obtain_type_display'] = static::$obtain_type[$item['obtain_type']] ?? '-';
            $item['use_type_display'] = static::$use_type[$item['use_type']] ?? '未使用';
            $item['status_display'] = static::$status[$item['status']] ?? '-';
            $item['use_time_display'] = '未使用';
            if ( $item['use_type'] > 0 ) {
                $item['use_time_display'] = date('Y年m月d日',strtotime($item['use_time']));
            }
            $item['coupon_value'] *= 1;
        }
        return $list;
    }

    /**
     * 增加领取记录
     * @Author   FW
     * @DateTime 2024-05-14
     * @Email    123763712@qq.com
     * @param    [type]           $uid         [description]
     * @param    [type]           $coupon_id   [description]
     * @param    integer          $obtain_type 1
     */
    public static function addObtainRecord($uid , $coupon_id , $obtain_type = 1)
    {
        $coupon = Coupon::where('id',$coupon_id)->find();
        if ( empty($coupon) ) throw new \Exception('代金券不存在');

        if ( $coupon->status != 1  ) throw new \Exception('代金券已被作废');

        $obtain_time = date('Y-m-d H:i:s');
        $expire_time = '';
        if ( $coupon->expire_type == 1 ) {
            $expire_time = date('Y-m-d 23:59:59' , strtotime($coupon->expire_value));
        }
        if ( $coupon->expire_type == 2 ) {
            $expire_time = date('Y-m-d 23:59:59' , strtotime($obtain_time . ' + ' . $coupon->expire_value . ' days'));
        }

        $status = static::STATUS_UNUSE;

        if ( strtotime($expire_time) < time() ) $status = static::STATUS_EXPIRED;

        return self::create([
            'coupon_id'  => $coupon_id,
            'uid'        => $uid,
            'obtain_type'=> $obtain_type,
            'obtain_time'=> $obtain_time,
            'expire_time'=> $expire_time,
            'status'     => $status,
        ]);
    }

    /**
     * 票券核销
     */ 
    public static function verify($id , $use_type = 2)
    {
        $record = self::alias('m')
        ->field('m.*,u.nickname,u.mobile,c.status as coupon_status,c.title as coupon_name,c.coupon_value')
        ->join('__USER__ u','m.uid = u.uid')
        ->join('__COUPON__ c','m.coupon_id = c.id')
        ->where('m.id',$id)
        ->find();
        if ( empty($record) ) throw new \Exception('领取记录不存在');
        if ( $record->coupon_status != 1 ) throw new \Exception('该券暂不可使用【1001】');
        if ( $record->status != 1 ) throw new \Exception('该券暂不可使用【1002】');
        if ( strtotime($record->expire_time) < time() ) throw new \Exception('该券已过期');

        $res = self::where('id',$id)->update(['status'=>self::STATUS_USED,'use_time'=>date('Y-m-d H:i:s'),'use_type'=>$use_type]);
        if ( $res !== false ) return true;

        return false;
    }
} //Class End
